package com.jeomo.mem.starter.timedtask;

import com.jeomo.common.quartz.starter.service.BaseJob;
import com.jeomo.mem.starter.entity.MemberCard;
import com.jeomo.mem.starter.entity.MemberPointsUpdate;
import com.jeomo.mem.starter.enums.MemberPointsSrcEnum;
import com.jeomo.mem.starter.mapper.MemberCardMapper;
import com.jeomo.mem.starter.service.IMemberCardService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 会员积分自动过期失效
 * @author:Jackpot
 * @create 2021-01-07 10:58
 * @description:
 */
public class PointsAutoExpiredJob implements Job {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private MemberCardMapper memberCardMapper;
    @Resource
    private IMemberCardService memberCardService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        List<MemberCard> memberCards = memberCardMapper.queryAllMemCards();
        int memberCardNum = memberCards.size();
        logger.info("自动处理过期的会员积分, 共计 "+memberCardNum+" 条会员信息 ");
        LocalDateTime now = LocalDateTime.now();
        int i =0;
        for (MemberCard memberCard : memberCards) {
            i += autoExpiredPoints(memberCard,now);
        }
        logger.info("[自动处理过期积分]任务执行完毕, 实际处理 "+i+" 条信息.");
    }


    public int autoExpiredPoints(MemberCard memberCard, LocalDateTime now){

        String cardNo = memberCard.getCardNo();
        Integer currPoints = memberCard.getPoints();
        int realPoints = memberCardService.getPoints(cardNo, now.toLocalDate());
        int pointsChange = currPoints - realPoints;
        if (pointsChange<=0) return 0;

        MemberPointsUpdate memberPointsUpdate = new MemberPointsUpdate();
        memberPointsUpdate.setCardNo(cardNo);
        memberPointsUpdate.setMemberNo(memberCard.getMemberNo());
        memberPointsUpdate.setMemberPhone(memberCard.getPhone());
        memberPointsUpdate.setMemberName(memberCard.getName());
        memberPointsUpdate.setLevelCode(memberCard.getMemLevel());
        memberPointsUpdate.setPointsChange(-pointsChange);
        memberPointsUpdate.setPointsOld(currPoints);
        memberPointsUpdate.setSrcCode("000000000");
        memberPointsUpdate.setSrcTypeCode(MemberPointsSrcEnum.EXPIRED.getCode());
        memberPointsUpdate.setHandleTime(now);
        memberPointsUpdate.setCardVersion(memberCard.getVersion());
        memberPointsUpdate.setOrg("000");//LoginSessionUtil.getCurrentLoginInfo().getOrgCode()
        memberCardService.updateMemberPoints(memberPointsUpdate);
        return 1;
    }
}
